<template>
  <div>
    <el-card v-if="Object.keys(wechatUserInfo).length > 0">
      <div class="title">
        <div class="left">
          <span>{{ wechatUserInfo.nickname || '无' }}</span>
          <el-icon
            size="18"
            color="#666666"
            @click="openDialog"
          >
            <EditPen />
          </el-icon>
        </div>
        <div class="right">
          <el-button
            type="danger"
            @click="wechatLogout()"
          >
            <el-icon><Refresh /></el-icon> 退出当前账户
          </el-button>
        </div>
      </div>
      <el-descriptions :column="1">
        <el-descriptions-item label="上次登录时间:">
          {{ wechatUserInfo.connect_time || '无' }}
        </el-descriptions-item>

        <el-descriptions-item label="启动提示语:">
          <el-tag
            v-for="(item, index) in (wechatUserInfo.start_keywords || [])"
            :key="index"
            type="warning"
            style="margin-right: 5px;"
          >
            {{ item }}
          </el-tag>
        </el-descriptions-item>

        <el-descriptions-item label="好友验证自动通过关键字:">
          <el-tag
            v-for="(item, index) in (wechatUserInfo.friend_verification_keywords || [])"
            :key="index"
            type="warning"
            style="margin-right: 5px;"
          >
            {{ item }}
          </el-tag>
        </el-descriptions-item>

        <el-descriptions-item label="好友验证通过自动回复:">
          {{ wechatUserInfo.friend_greetings || '' }}
        </el-descriptions-item>

        <el-descriptions-item label="微信UID:">
          {{ wechatUserInfo.user_id || '*' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="des">
      <el-row>
        <el-col :span="12">
          <p>📢📢📢：项目暂时只提供一个账号的测试和使用；重新登录不同账户将替换原有机器人。</p>
        </el-col>
        <el-col
          :span="2"
          :offset="22"
        >
          <el-button
            type="info"
            @click="wechatLoginCode()"
          >
            <el-icon><Refresh /></el-icon> 账户登录
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog
      v-model="dialogFormVisible"
      title="修改机器人配置"
      width="550"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="140px"
      >
        <el-form-item
          label="机器人名称"
        >
          <el-input
            v-model="formData.nickname"
            disabled
            placeholder="请输入"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="启动提示语"
          prop="start_keywords"
        >
          <el-input-tag
            v-model="formData.start_keywords"
            clearable
            placeholder="请输入关键字"
          />
        </el-form-item>

        <el-form-item
          label="好友通过关键字"
          prop="friend_verification_keywords"
        >
          <el-input-tag
            v-model="formData.friend_verification_keywords"
            clearable
            placeholder="请输入关键字"
          />
        </el-form-item>

        <el-form-item
          label="好友通过自动回复"
          prop="friend_greetings"
        >
          <el-input
            v-model="formData.friend_greetings"
            placeholder="请输入"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button
            type="primary"
            @click="dialogcConfirm(formRef)"
          >
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="dialogWechatCodeVisible"
      title="微信机器人扫码登录"
      width="450"
      :before-close="dialogWechatCodeHandleClose"
    >
      <div v-if="wechatCodeUrl.length > 0">
        <img
          :src="wechatCodeUrl"
          alt="QR Code"
        >
      </div>
      <el-button
        type="success"
        @click="wechatLoginCode()"
      >
        <el-icon><Refresh /></el-icon> 刷新二维码
      </el-button>
    </el-dialog>
  </div>
</template>

<script setup lang="js">
import { onMounted, reactive, ref, toRaw, watch } from 'vue'
import { checkWechatLoginStatus, getWechatLoginCode, getWechatUserInfo, logout, updateWechatUserTemp } from '@/apis/console'
import { userStore } from '@/stores'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, EditPen } from '@element-plus/icons-vue'

const user = userStore()

const formRef = ref()
const dialogFormVisible = ref(false)
const wechatUserInfo = ref({})
const dialogWechatCodeVisible = ref(false)
const wechatCodeUrl = ref('')

const formData = reactive({
  nickname: '',
  friend_greetings: '',
  friend_verification_keywords: [],
  start_keywords: []

})

const rules = reactive({
  friend_greetings: [{ required: true, message: '请输入问候语', trigger: 'blur' }],
  friend_verification_keywords: [{ required: true, message: '请输入好友通过关键字', trigger: 'blur' }],
  start_keywords: [{ required: true, message: '请输入启动关键字', trigger: 'blur' }]
})

onMounted(getData)

function openDialog () {
  Object.assign(formData, toRaw(wechatUserInfo.value))
  dialogFormVisible.value = true
}

function dialogcConfirm (formEl) {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      updateWechatUserTemp(formData).then(res => {
        if (res.data.code !== 0) {
          console.log(res.data.data)
          ElMessage.error('操作失败~')
        } else {
          dialogFormVisible.value = false
          ElMessage.success('操作成功~')
        }
      })
    }
  })
}

function wechatLoginCode () {
  getWechatLoginCode().then(res => {
    if (res.data.code !== 0) {
      ElMessage.error(res.data.data)
    } else {
      if (res.data.data.result_type.loginType === 'hot') {
        ElMessage.success('账号已经存在登录用户~请退出原有账号~')
      } else {
        dialogWechatCodeVisible.value = true
        wechatCodeUrl.value = res.data.data.result_type.codeUrl
      }
    }
  })
}

function dialogWechatCodeHandleClose () {
  checkWechatLoginStatus().then(res => {
    if (res.data.code !== 0 || !res.data.data.status) {
      ElMessageBox.confirm(
        '微信登录尚未通过，点击确定关闭二维码?',
        '',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        dialogWechatCodeVisible.value = false
      })
    } else {
      ElMessage.success('账号已经登录状态~')
      getData()
      dialogWechatCodeVisible.value = false
    }
  })
}

function wechatLogout () {
  ElMessageBox.confirm(
    '确定要退出当前微信?',
    '',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    logout().then(res => {
      if (res.data.code !== 0) {
        ElMessage.error(res.data.data)
      } else {
        wechatUserInfo.value = {}
        ElMessage.success('操作成功~')
      }
    })
  })
}

function getData () {
  getWechatUserInfo().then(res => {
    if (res.data.code !== 0) {
      ElMessage.error('暂时没有登陆的账户~')
    } else {
      wechatUserInfo.value = res.data.data
    }
  })
}

watch(
  () => user.userInfo.robot_id,
  (val) => val && getData()
)
</script>

<style lang="scss" scoped>
.title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
  .left {
    display: flex;
    align-items: center;
    span {
      margin-right: 8px;
      font-size: 20px;
      color: #1890ff;
    }
  }
}
.des {
  margin-top: 10px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
